package com.cy.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.cy.service.ConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @ClassName ConsumerController
 * @Description:类描述
 * @Author Tedu
 * @Date 2021/6/1 10:47
 * @Version V1.0
 **/
@RestController
public class ConsumerController{
    /*AtomicLong对象提供了一种线程安全的-自增自减操作*/
    //测试预热模式限流CAS算法
    private AtomicLong atomicLong=new AtomicLong(0);
    //链路模式限流测试
    @Autowired
    private ConsumerService consumerService;

    @Value("${spring.application.name}")
    private String appName;

    /*LoadBalancerClient此对象基于服务名可找到服务实例
     * */
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    //热点链路限流测试
    @GetMapping("/consumer/findById")
    @SentinelResource("doFindById")
    public String doFindById(@RequestParam("id") Integer id){
        return "hot id is"+id;
    }

    @GetMapping("/consumer/doRestEcho")
    public String doRestEcho(){

        //模拟慢调用(请求响应时间让它长一点)
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //测试预热限流模式
        System.out.println(atomicLong.incrementAndGet());
        //链路模式限流测试
        consumerService.doGetResource();

        //基于服务名获取服务实例(不同的服务实例端口肯定不同) 构建url
        ServiceInstance serviceInstance =
                loadBalancerClient.choose("nacos-provider");
        String url =
                String.format("http://%s:%s/provider/echo/%s",
                        serviceInstance.getHost(), serviceInstance.getPort(), appName);
        System.out.println("request url:"+url);
        //restTemplate向服务提供方发起请求
        //url请求地址
        // String.class为请求服务的响应结果类型
        return restTemplate.getForObject(url, String.class);
    }

}
